//
//  NewFeatureViewController.swift
//  sinaWeiBo
//
//  Created by smartlei on 15/10/17.
//  Copyright © 2015年 smartlei. All rights reserved.
//

import UIKit

private let NewFeatureCellReuseID = "NewFeatureCellReuseID"
private let NewFeatureCellCount = 4

class NewFeatureViewController: UICollectionViewController {

    //重写init构造函数
     init() {
        
        let layout = UICollectionViewFlowLayout()
        //间距10
        layout.minimumLineSpacing = 0
        //cell大小
        layout.itemSize = UIScreen.mainScreen().bounds.size
        //滚动方向
        layout.scrollDirection = .Horizontal
        //调用父类初始化
        super.init(collectionViewLayout: layout)
        
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.delaysContentTouches = false
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(NewFeatureCollectionCell.self, forCellWithReuseIdentifier: NewFeatureCellReuseID)

        // Do any additional setup after loading the view.
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return NewFeatureCellCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NewFeatureCellReuseID, forIndexPath: indexPath) as! NewFeatureCollectionCell
        
        cell.imgIndex = indexPath.item
        
        //cell.backgroundColor = indexPath.item % 2 ? UIColor.redColor() : UIColor.greenColor()
    
        return cell
    }
    
    //最后一页停止滚动执行动画
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        //转化结果，计算第几页
        let pageIndex = Int(scrollView.contentOffset.x / scrollView.bounds.size.width)
        
        
        if pageIndex + 1 != 4 {
            //没有到达最后一页
            return
        }
        
        //取出cell
        let cell = collectionView?.cellForItemAtIndexPath(NSIndexPath(forItem: pageIndex, inSection: 0)) as! NewFeatureCollectionCell
        
        //让cell开始执行动画
        cell.startButtonAnimate()
        
    }

    //隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }

}

class NewFeatureCollectionCell: UICollectionViewCell {
    
   private lazy var imgView = UIImageView()
    //注意需要: UIButton  不然报错
    lazy var loginBtn: UIButton = UIButton(title: "欢迎体验", titleColor: UIColor.blackColor(), backImgName: "new_feature_finish_button")
    
    var imgIndex: Int = 0 {
        
        didSet {
            //隐藏
            loginBtn.hidden = true
            imgView.image = UIImage(named: "new_feature_\(imgIndex+1)")
        }
    }
    
    //重写父类方法
    override init(frame: CGRect) {
      super.init(frame: frame)
        
        //添加控件
        setCellUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //按钮点击事件
    @objc private func loginBtnClick() {
       NSNotificationCenter.defaultCenter().postNotificationName("WBNSNotificationCenterChangeViewController", object: nil)
    }
    
    //设置界面UI上控件
    private func setCellUI() {
        
        addSubview(imgView)
        addSubview(loginBtn)
        
        loginBtn.addTarget(self, action: "loginBtnClick", forControlEvents: .TouchUpInside)
        
        imgView.frame = bounds
        //添加约束
        loginBtn.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_bottom).multipliedBy(0.8)
            make.width.equalTo(150)
            make.height.equalTo(35)
            
        }
        imgView.backgroundColor = UIColor.orangeColor()

    }

    //cell执行动画
    private func startButtonAnimate() {
        //执行动画的时候页面已经完全显示完全了
        //不隐藏按钮
        loginBtn.hidden = false
        //动画按钮从无变有
        loginBtn.transform = CGAffineTransformMakeScale(0, 0)
        //动画未完成前禁止点击
        loginBtn.userInteractionEnabled = false
        //剪成圆角
        loginBtn.layer.cornerRadius = 5
        loginBtn.layer.masksToBounds = true
        
       //执行UIView的类动画
        UIView.animateWithDuration(1.0, //动画持续时间
            delay: 0,   //动画开始执行前的延时
            usingSpringWithDamping: 0.75,
            initialSpringVelocity: 10,
            options: [],
            animations: { () -> Void in
                //恢复到带身份证的transform属性
                self.loginBtn.transform = CGAffineTransformIdentity
                
            }) { (_) -> Void in
                //按钮使能交互
                self.loginBtn.userInteractionEnabled = true
        } 
    }
}
